package com.dsideal.cloud.cas.client.utils;

import com.dsideal.cloud.auth.core.config.UserAuthenticationConfig;
import com.dsideal.cloud.cache.api.CacheApi;
import com.dsideal.cloud.cas.client.cache.RedisUserCache;
import com.dsideal.cloud.cas.client.properties.KeyConfiguration;
import com.dsideal.cloud.common.util.StringUtils;
import org.apache.commons.codec.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author suny
 */
@Configuration
public class AuthServerRunner implements CommandLineRunner {
    @Autowired
    private KeyConfiguration keyConfiguration;

    @Autowired
    private UserAuthenticationConfig userAuthenticationConfig;
    @Autowired
    private RedisUserCache redisUserCache;

    @Autowired
    private CacheApi cacheApi;

    private static final String prikey="pri";
    private static final String pubkey="pub";
//    private static final String cacheKey="userPubKey";
    @Override
    public void run(String... args) throws Exception {
       String cacheUserPubKey= cacheApi.get(pubkey);
        if(StringUtils.isEmpty(cacheUserPubKey)){
            Map<String, byte[]> keyMap = RsaKeyHelper.generateKey(keyConfiguration.getUserSecret());
            keyConfiguration.setUserPriKey(keyMap.get(prikey));
            keyConfiguration.setUserPubKey(keyMap.get(pubkey));
            String pub = new String(keyMap.get(pubkey), CharEncoding.ISO_8859_1);
            String pri = new String(keyMap.get(prikey), CharEncoding.ISO_8859_1);

//            cacheApi.set(cacheKey, pub, -1);
            this.userAuthenticationConfig.setPubKeyByte(keyMap.get(pubkey));

            cacheApi.set(pubkey, pub, -1);
            cacheApi.set(prikey, pri, -1);
           /* keyMap = RsaKeyHelper.generateKey(keyConfiguration.getServiceSecret());
            keyConfiguration.setServicePriKey(keyMap.get(prikey));
            keyConfiguration.setServicePubKey(keyMap.get(pubkey));*/
        }else{
            //redis 中相关数据以被缓存
            keyConfiguration.setUserPriKey(cacheApi.get(prikey).getBytes(CharEncoding.ISO_8859_1));
            keyConfiguration.setUserPubKey(cacheApi.get(pubkey).getBytes(CharEncoding.ISO_8859_1));
            this.userAuthenticationConfig.setPubKeyByte(cacheApi.get(pubkey).getBytes(CharEncoding.ISO_8859_1));
        }
    }
}
